package juc;

import org.junit.Test;
import util.ThreadUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author wuguojian
 * @description 读写锁实例
 * @date 2022/11/23 下午3:55
 **/
public class ReadWriteLockTest {
    final static Map<String, String> DATA = new HashMap<String, String>();
    final static ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();
    final static Lock READ_LOCK = LOCK.readLock();
    final static Lock WRITE_LOCK = LOCK.writeLock();

    public static Object put(String key, String val){
        WRITE_LOCK.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 获取写锁");
            ThreadUtil.sleep(1000L);
            return DATA.put(key, val);
        }finally {
            WRITE_LOCK.unlock();
        }
    }

    public static Object get(String key){
        READ_LOCK.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 获取读锁");
            return DATA.get(key);
        }finally {
            READ_LOCK.unlock();
        }
    }

    @Test
    public void test(){
        Runnable readRunnable = ()->{
            get("key");
        };
        Runnable writeRunnable = ()->{
            put("key", "value");
        };
        for (int i = 0; i < 5; i++) {
            new Thread(readRunnable, "读线程："+i).start();
        }
        for (int i = 0; i < 5; i++) {
            new Thread(writeRunnable, "写线程："+i).start();
        }
    }
}
